﻿using System.Diagnostics;
using System.Windows.Automation;

namespace QuickUIT
{
    public class BaseState
    {
        private Process _program;
        private readonly string _programPath; 
        private readonly IAutomationElementSearchCriteria _searchCriteria;

        private bool _hasStarted; 

        public BaseState(string programPath, string locator)
        {
            _programPath = programPath;
            _searchCriteria = LocatorParser.GetSearchCriteria(locator);
        }

        public void Execute()
        {
            var eventHandler = new AutomationEventHandler(OnWindowOpen);
            Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, TreeScope.Children, eventHandler);
            if (_programPath != null)
            {
                _program = Process.Start(_programPath);
            }
            var timer = new AutomationTimer(30000); 
            timer.Start();
            while (!timer.HasTimedOut())
            {
                if (_hasStarted)
                {
                    Automation.RemoveAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, eventHandler);
                    return;
                } 
                System.Threading.Thread.Sleep(500);
            }
            Automation.RemoveAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, eventHandler);
        }

        public void Cleanup()
        {
            if (_program != null)
            {
                _program.Kill();   
            }
        }

        private void OnWindowOpen(object src, AutomationEventArgs e)
        {
            AutomationElement sourceElement;
            try
            {
                sourceElement = src as AutomationElement;
            }
            catch (ElementNotAvailableException)
            {
                return;
            }

            if (e.EventId == WindowPattern.WindowOpenedEvent)
            {
                if (_searchCriteria.Matches(sourceElement))
                {
                    _hasStarted = true; 
                }
            }
        }
    }
}
